import urllib2

class WebLoginClient:
    def __init__(self,url_login,url_login_format,url_verify,file_verify='./i.jpg'):
        self.url_login = url_login
        self.url_login_format = url_login_format
        self.url_verify = url_verify
        self.file_verify = file_verify
        self.cookies = urllib2.HTTPCookieProcessor()
        self.opener = urllib2.build_opener(self.cookies)
        self.isLoad = False

    def fetch_verifycode(self):
        f_img = open(self.file_verify,'wb')
        f = self.opener.open(self.url_verify)
        f_img.write(f.read())
        f_img.close()
        f.close()
        self.isLoad = True

    def login(self,uin,pwd,verifycode):
        if not self.isLoad:
            return False
        req = urllib2.Request(url=self.url_login, data=self.url_login_format%(uin,pwd,verifycode))
        f = self.opener.open(req)
        print f.read()
        f.close()


    

if __name__=='__main__':
    #before login
    import urllib
    f = urllib.urlopen('http://portal.widget.xunlei.com/cgi-bin/cgi_user_image_audit?action=list&flag=list')
    print f.read()
    f.close()
    
    #prepare login
    url_login='http://login.xunlei.com/bloglogin/'
    url_login_format='u=%s&p=%s&verifycode=%s'
    url_verify='http://verify.xunlei.com/image/'
    xl_client = WebLoginClient(url_login,url_login_format,url_verify)
    xl_client.fetch_verifycode()
    print 'plz. input uin:'
    uin = raw_input()
    print 'plz. input pwd:'
    pwd = raw_input()
    print 'plz. input verifycode:'
    verifycode = raw_input()
    xl_client.login(uin, pwd, verifycode)

    #after login
    req = urllib2.Request(url='http://portal.widget.xunlei.com/cgi-bin/cgi_user_image_audit',
                          data='action=list&flag=list&row_per_page=3&page=1',
                          headers={'Content-Type' : 'text/xml'})
    f = xl_client.opener.open(req)
    print f.read()
    f.close()

    
    req = urllib2.Request(url='http://portal.widget.xunlei.com/cgi-bin/cgi_user_image_audit',
                          data='action=list&flag=list&row_per_page=3&page=2',
                          headers={'Content-Type' : 'text/xml'})
    f = xl_client.opener.open(req)
    print f.read()
    f.close()

    
